<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('translationImage.fqc')"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="page-auto" :style="'height: calc(100vh - '+ navHeight +'px);'">
				<!-- 调拨单信息 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{$t('translationImage.checkoutInfo')}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{data.fqcInfo.materialCode}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{data.fqcInfo.materialSpec}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{data.fqcInfo.materialName}}
					</view>
				</view>
				<view class="element-auto">
					<view class="h-table gui-margin-top" style="background: #fff;">
						<view class="h-tr h-tr-3 h-thead ">
							<view class="h-td">{{$t('translationImage.serialNumber')}}</view>
							<view class="h-td">{{$t('translationImage.testItem')}}</view>
							<view class="h-td">{{$t('translationImage.standard')}}</view>
							<view class="h-td">{{$t('translationImage.inspectionResult')}}</view>
							<view class="h-td">{{$t('translationImage.supportingInfo')}}</view>
						</view>
						<view class="h-tr h-tr-3" v-for="(x,i) in data.testItem" :key="i"
							:class="{'passclass' : data.qualifiedList[i] == 'pass'},{'failClass' : data.qualifiedList[i] == 'fail'}">
							<view class="h-td">{{i+1}}</view>
							<view class="h-td">{{x.checkProjectName}}</view>
							<view class="h-td">{{x.standardItem}}</view>
							<view class="h-td">
								<view class="gui-flex gui-align-items-center" v-if="!data.isResult">
									<input v-if="x.resultType == 'text'" type="text"
										style="width: 120rpx;font-size: 14px;" v-model="x.checkResult">
									<input v-else-if="x.resultType == 'number'" type="number"
										style="width: 120rpx;font-size: 14px;" v-model="x.checkResult">
									<superweiCombox v-else-if="x.resultType == 'option'"
										style="text-align: right;width: 120rpx;padding:0"
										:candidates="data.selectedList" :placeholder="$t('translationImage.choose')" :isJSON="true" keyName="text"
										@select="selectFn($event,i)"></superweiCombox>
								</view>
								<view class="gui-flex gui-align-items-center" v-else>
									{{x.checkResult == 'pass' ? $t('translationImage.qualified') : (x.checkResult == 'fail' ? $t('translationImage.qualifiedNo')  : x.checkResult)}}
								</view>
							</view>
							<view class="h-td">
								<view class="custom-td-operate" @click="rowClick(i)">
									{{$t('translationImage.operation')}}
								</view>
							</view>
						</view>
					</view>
					<view class="iqc-res" v-if="!data.isResult">
						{{$t('translationImage.conclusion')}}：{{totalQualified}}
					</view>
				</view>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box" v-if="!data.isResult">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">
						{{$t('calendar.submit')}}
					</view>
				</view>
			</view>
			<!-- 页面弹窗 -->
			<uni-popup ref="inputDialog" type="center">
				<view class="input-dialog-box">
					<view class="input-dialog-content">
						<uni-section :title="$t('translationImage.selectImg')" type="line">
							<view class="example-body">
								<uni-file-picker :auto-upload='false' @select="select" v-model="data.uploadImg"
									:readonly="data.isResult"></uni-file-picker>
								<view style="line-height: 30px;" v-if="!data.uploadImg.length && data.isResult">
									{{$t('translationImage.notAvailableImg')}}
								</view>
							</view>
						</uni-section>
					</view>
					<view class="input-dialog-footer" v-if="!data.isResult">
						<view class="input-dialog-button" @click="cancelFn">
							{{$t('calendar.cancel')}}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="confirmFn">
							{{$t('calendar.confirm')}}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
	import {
		TEST_URL,
		PROD_URL,
		IMG_BASE_URL
	} from '@/constant/config.js'
	import { basPdaOperationLogFn } from '@/utils/index.js';
	import { OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'
	import {
		TOKEN
	} from '@/constant/index.js';
	import {
		navigate,
		navigateBack
	} from '@/utils/routerSkip.js';
	import {
		reactive,
		ref,
		onMounted,
		computed,
		watchEffect,
		toRaw
	} from 'vue';
	import {
		findRelationByCode,
		insertFqcCheck
	} from '@/api/api.js'
	import {
		getDataDictionaryFn
	} from '@/utils/index.js'
	import {
		useStore
	} from "vuex";
	import superweiCombox from '@/components/superweiCombox';
	//JS国际化引入
	import { useI18n } from 'vue-i18n';
	components: {
		superweiCombox
	}
	const { t } = useI18n();

	let store = useStore()
	const props = defineProps({
		materialCode:String,
	})
	let inputDialog = ref(null)
	let data = reactive({
		testItem: [], //检测数据集合
		uploadImg: [],
		selectedList: [{
			text: t('translationImage.qualified'),
			value: 'pass'
		}, {
			text: t('translationImage.qualifiedNo'),
			value: 'fail'
		}, ],
		imgIndex: 0, //用户当前点击行数索引
		qualifiedList: [], //每一项的检验结果集合
		isPassImgRequired: false, //判断合格是否必须上传图片
		isFailImgRequired: false, //判断不合格是否必须上传图片
		isResult: false //判断是否有结果
	})
	data.fqcInfo = computed(() => {
		return store.state.fqcInfo
	})
	// 判断所有数据是否合格
	const totalQualified = computed(() => {
		if(!data.qualifiedList.length){
			return ''
		}
		let isTrue = data.qualifiedList.every(x => {
			return x === 'pass'
		})
		let isFail = data.qualifiedList.some(x => {
			return x === 'fail'
		})
		if (isTrue) {
			return t('translationImage.qualified')
		} else if (isFail) {
			return t('translationImage.qualifiedNo')
		} else {
			return ''
		}
	})
	const navHeight = computed(() => {
		return store.state.navHeight
	})
	// 算出每行合格量和总合格数
	watchEffect(() => {
		console.log(data.testItem)
		//pass 合格 ; fail 不合格
		data.testItem.forEach((x, i) => {
			console.log(x.checkResult, i, 'watchEffect')
			if (x.checkResult) {
				switch (x.resultType) {
					case 'text':
						//如果是文字类型，不做判断，默认合格
						data.qualifiedList[i] = 'pass'
						break;
					case 'number':
						//如果是数值类型，判断是否在合格区间
						let a = x.standardItem.split('~')
						let b = Number(a[0])
						let c = Number(a[1])
						let d = Number(x.checkResult)
						if (!isNaN(d) && d >= b && d <= c) {
							data.qualifiedList[i] = 'pass'
						} else {
							data.qualifiedList[i] = 'fail'
						}
						break;
					case 'option':
						data.qualifiedList[i] = x.checkResult
						break;
					default:
						break;
				}
			} else {
				data.qualifiedList[i] = ''
			}
		})
	})
	onMounted(() => {
		findRelationByCodeFn()
		getInitData()
		setTimeout(() => {
			console.log(data.fqcInfo)
		}, 2000)
	})
	const getInitData = async () => {
		// 控制PDA质检画面的佐证资料是否需要上传照片
		let info = await getDataDictionaryFn('SupportingInformation')
		info.forEach(x => {
			if (x.value === 'pass') {
				data.isPassImgRequired = x.selected
			} else if (x.value === 'fail') {
				data.isFailImgRequired = x.selected
			}
		})
		console.log(data, 'getInitData')
	}
	//提交数据
	const submit = () => {
		// 检测每行检测结果是否填写
		let isTrue = data.testItem.every(x => {
			return x.checkResult
		})
		if(!data.testItem.length){
			isTrue = false
		}
		console.log(isTrue)
		if (!isTrue) {
			uni.showToast({
				title: t('JsInternational.plsFillAll'),
				icon: 'none'
			})
			return
		}
		// 检测合格结果佐证资料是否必填
		if (!data.isPassImgRequired) {
			if (!data.testItem.every(x => x.imgList.length)) return uni.showToast({
				title: t('materials.pleaseUploadSupporting'),
				icon: 'none'
			})
		}
		// 检测不合格结果佐证资料是否必填
		if (!data.isFailImgRequired) {
			if (!data.testItem.every(x => x.imgList.length)) return uni.showToast({
				title: t('materials.pleaseUploadSupportingInfo'),
				icon: 'none'
			})
		}
		data.testItem.forEach(x => {
			let arry = x.imgList.map(x => x.url)
			console.log(arry)
			x.supportImage = arry.join()
		})
		console.log(data.testItem)
		let param = {
			materialCode: data.fqcInfo.materialCode,
			materialName: data.fqcInfo.materialName,
			materialSpec: data.fqcInfo.materialSpec,
			currentQty: data.fqcInfo.currentQty,
			unit: data.fqcInfo.unit,
			qmsRelationDS: toRaw(data.testItem),
			barcodeList: data.fqcInfo.child
		}
		console.log(param)
		// 添加加载框
		uni.showLoading({
			title: 'loading',
			mask:true
		});
		insertFqcCheck(param).then(res => {
			try {
				let inputParameter = JSON.stringify(param)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '成品检验'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode:res.status,//返回状态
					errorMessage:res.message,//错误信息
					isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType:OPERATION_COMMIT
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			console.log(res, 'paramparamparam')
			if (res.status == 200) {
				//隐藏加载框
				uni.hideLoading();
				store.commit('deleteFqcScanList', data.fqcInfo.child);
				uni.showToast({
					title: t('smashRemoval.submitSuccessfully'),
					icon: 'none',
					duration:2000,
					complete: () => {
					    setTimeout(()=>{
							navigateBack()
						},1000)

					}
				})
			} else {
				uni.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		})
	}
	// 上传图片获取开始上传
	const select = (e) => {
		const tempFilePaths = e.tempFilePaths;
		let isDev = process.env.NODE_ENV === 'development';
		let baseUrl = isDev ? TEST_URL : PROD_URL
		let token = uni.getStorageSync(TOKEN);
		let formData = {
			bizId: data.fqcInfo.materialCode,
			bizType: 'qms_fqc_check_h'
		}
		uni.showLoading({
			title: t('JsInternational.uploading')
		});
		for (var i in tempFilePaths) { //多文件
			uni.uploadFile({
        url: baseUrl + '/system/oss/oss-simple', //上传接口
				name: 'file',
				header: {
					// "content-type": "multipart/form-data",
					'token': token
				},
				filePath: tempFilePaths[i],
				formData: formData,
				success: (uploadFileRes) => {
					uni.hideLoading();
					const back = JSON.parse(uploadFileRes.data);
					if (back.statusCode == 200) {
						// let imgPath = IMG_BASE_URL + back.filePath;
            let imgPath = back.data;
						console.log(imgPath, 'imgPathimgPathimgPath')
						data.uploadImg.push({
							name: '',
							extname: 'png',
							url: imgPath
						})
						console.log(data.uploadImg);
					} else {
						uni.showToast({title:back.message, icon:"none"});
					}
				},
				fail: () => {
					uni.hideLoading();
					uni.showToast(t('JsInternational.pictureUploading'))
				},
				complete: function() {
					uni.hideLoading();
				}
			});
		}
	}
	// 获取物料检测项
	const findRelationByCodeFn = () => {
		let parmes = {
			relationItemCode: props.materialCode,
			checkType: 'FQC'
		}
		findRelationByCode(parmes).then(res => {
			try {
				let inputParameter = JSON.stringify(parmes)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '成品检验'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode:res.status,//返回状态
					errorMessage:res.message,//错误信息
					isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType:OPERATION_LOOK
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			if (res.status == 200) {
				if (!res.data.length) return
				data.isResult = res.data[0].checkResult != null;
				data.testItem = res.data;
				data.qualifiedList = []
				data.testItem.forEach(x => {
					x.imgList = [];
					data.qualifiedList.push('')
					if (x.supportImage) {
						x.imgList = x.supportImage.split(',').map(x => {
							return {
								name: '',
								extname: 'png',
								url: x
							}
						})
					}
				})
			} else {
				uni.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		})
	}
	// 下拉列表选择
	const selectFn = (e, index) => {
		data.testItem[index].checkResult = e.value
		console.log(e, index)
	}
	// 表格点击操作
	const rowClick = (index) => {
		data.imgIndex = index;
		data.uploadImg = data.testItem[index].imgList;
		console.log(data.uploadImg, 'data.uploadImg');
		inputDialog.value.open();
	}
	const cancelFn = () => {
		inputDialog.value.close();
		data.uploadImg = []
	}
	const confirmFn = () => {
		data.testItem[data.imgIndex].imgList = data.uploadImg
		inputDialog.value.close();
	}
</script>

<style scoped lang="scss">
	.custom-table {
		display: table;
		// border-collapse: collapse;
		background: #fff;
		font-size: 28rpx;
		width: 100%;
		overflow: hidden;

		.custom-tr {
			display: table-row;
		}

		.custom-th,
		.custom-td {
			height: 68rpx;
			line-height: 68rpx;
			display: table-cell;
			padding: 0 10rpx;
			border: 1px solid #ebeef5;
		}

		.custom-th {
			font-weight: 600;
		}

		.custom-td-operate {
			display: inline-block;
			padding: 10rpx 20rpx;
			border-radius: 8rpx;
			background: #3970E6;
			color: #fff;
			line-height: 28rpx;
		}
	}

	.iqc-res {
		text-align: right;
		font-size: 32rpx;
		padding: 30rpx;
	}

	.custom-td-operate {
		display: inline-block;
		padding: 10rpx 20rpx;
		border-radius: 8rpx;
		background: #3970E6;
		color: #fff;
		line-height: 28rpx;
	}
</style>
